<template>
  <div class="sub-form-wrapper">
    <el-card>
      <template #header>
        <div @click="handleSelectCol(field)">
          {{ field.label || "全部" }}
        </div>
      </template>
      <RenderFormFieldList
        v-if="field.genConfig.subFormType === 'singleRow'"
        :layout-config="layoutConfig"
        :field="field"
        @selectField="handleSelectCol"
      />
      <el-table
        v-else
        ref="tableRef"
        :data="dataSource"
        style="width: 100%"
        border
      >
        <el-table-column
          v-for="column in field.fieldList"
          :key="column.formKey"
          :width="column.label === '序号' ? '60px' : 'auto'"
        >
          <template #header>
            <div style="cursor: pointer" @click="handleSelectCol(column)">
              {{ column.formKey === "action" ? "操作" : column.label }}
            </div>
          </template>
          <template #default="scope">
            <template v-if="column.label === '操作'">
              <a> 删除 </a>
            </template>
            <template v-else-if="column.label === '序号'">
              <span>
                {{ scope.$index + 1 }}
              </span>
            </template>
            <template v-else>
              <field-renderer
                isPreview
                :showLabel="false"
                :formLayout="layoutConfig.formLayout"
                :field="column"
                :formData="scope.row"
                v-model:value="scope.row[column.formKey]"
              />
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { computed } from "vue";
import FieldRenderer from "./FieldRenderer.vue";
import RenderFormFieldList from "./RenderFormFieldList.vue";

const props = defineProps({
  layoutConfig: { type: Object, default: () => ({}) },
  field: { type: Object, default: () => ({}) },
});
const emits = defineEmits(["selectField", "click"]);

const dataSource = computed(() => {
  const dataItem = {};
  props.field.fieldList.forEach((item) => {
    dataItem[item.formKey] = "";
  });
  return [dataItem, { ...dataItem }];
});

function handleSelectCol(record) {
  emits("selectField", record);
}
function handleClick() {
  console.log("🚀 ~ handleClick ~ handleClick:");
  emits("click", props.handleClick);
}
</script>

<style scoped lang="less">
.sub-form-wrapper {
  ::v-deep {
    .el-card__body {
      padding: 10px;
    }
    .el-table .el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
